package com.tz.crm.controller;

import com.alibaba.fastjson.JSON;
import com.tz.crm.entity.dto.AjaxResult;
import com.tz.crm.utils.RequestTypeThreadLocal;
import org.apache.log4j.Logger;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * ExceptionAdvice
 * 负责处理项目全局的异常
 */
@ControllerAdvice
public class ExceptionAdvice {

    private static final Logger LOGGER = Logger.getLogger(ExceptionAdvice.class);

    /**
     * 检测到DataIntegrityViolationException异常时 返回错误信息
     *
     * @param ex       DataIntegrityViolationException异常
     * @param response HttpServletResponse
     * @return 视图路径或 null
     * @throws IOException 异常
     */
    @ExceptionHandler(DataIntegrityViolationException.class)
    public String dataIntegrityViolation(DataIntegrityViolationException ex, HttpServletResponse response) throws IOException {
        //打印异常信息
        ex.printStackTrace();
        String str = RequestTypeThreadLocal.get();
        //如果是异步请求
        if (str.equals(IConst.REQUEST_ASYNCHRONOUS)) {
            LOGGER.error("数据存在关联,删除失败");
            Object obj = "数据存在关联,删除失败";
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage((String) obj);
            if (response != null) {
                response.setContentType("application/json;charset:utf-8");
                PrintWriter out = response.getWriter();
                out.println(JSON.toJSONString(ajaxResult));
                out.flush();
                out.close();
            }
            return null;
        } else {
            return "error/data_violation";
        }
    }

}
